package com.flatfish.acvsystem.service.impl;

import java.io.File;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.flatfish.acvsystem.dao.IVerifyDao;
import com.flatfish.acvsystem.model.ACVApkAuthEntity;
import com.flatfish.acvsystem.service.IVerifyService;
import com.flatfish.acvsystem.uitl.ACVSystemConst;
import com.flatfish.acvsystem.uitl.ApkUtils;
import com.flatfish.acvsystem.uitl.DownloadFileUtils;
import com.flatfish.acvsystem.vo.ACVApkAuthVO;

/**
 * @author luohuida
 * @Time   Mar 7, 2015
 * @Email  luo.archer@gmail.com
 * @Description <b>验证业务逻辑接口实现</b>
 */
@Service
@Transactional(readOnly=false)
public class VerifyServiceImpl implements IVerifyService {
	
	@Autowired
	private IVerifyDao verityDAOImpl;
	
	/**
	 * @param url:http://app.scnu.edu.cn/apk/scnuapp.apk
	 * @Description <b></b>
	 * @see com.flatfish.acvsystem.service.IVerifyService#downloadApk(java.lang.String)
	 */
	@Override
	public void verityApkByURL(String apkUrl) {
		if(null == apkUrl) return;
		
		String fileName = apkUrl.substring(apkUrl.lastIndexOf("/")+1);
		String filePath = DownloadFileUtils.downloadFileByURL(fileName, apkUrl);
		if(null != filePath){
			ACVApkAuthVO acvVo = ApkUtils.getApkMetaInfo(filePath);
			if(null==acvVo) return;
			acvVo.setUrl(apkUrl);
			
			ACVApkAuthEntity acvEn = new ACVApkAuthEntity();
			acvVo.setVOToEntity(acvEn);
			try {
				verityDAOImpl.save(acvEn);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param path
	 * @Description <b></b>
	 * @see com.flatfish.acvsystem.service.IVerifyService#verityApkByFile(java.lang.String)
	 */
	@Override
	public void verityApkByFile(CommonsMultipartFile[] files) {
		if(null==files || files.length<=0) return;
		
        for(CommonsMultipartFile file:files){
        	if (!file.isEmpty()) {  
                String path = ACVSystemConst.STORAGE_PATH + file.getOriginalFilename();  
                File localFile = new File(path);  
                try {  
                    file.transferTo(localFile);  
                    ACVApkAuthVO acvVo = ApkUtils.getApkMetaInfo(path);
        			if(null==acvVo) return;
        			
        			ACVApkAuthEntity acvEn = new ACVApkAuthEntity();
        			acvVo.setVOToEntity(acvEn);
        			try {
        				verityDAOImpl.save(acvEn);
        			} catch (Exception e) {
        				e.printStackTrace();
        			}
                    
                } catch (IllegalStateException e) {  
                    e.printStackTrace();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            } 
        }
		
	}

}
